import {
	setCookie,
	removeCookie
} from '@/libs/cookies'
import {
	setStore,
	removeAllStore,
} from '@/libs/storage'
import cookieparser from 'cookieparser';
import app from './modules/app';
import data from './modules/data';
export const state = () => ({
	userInfo: null,
	seo: {
		title: '',
		keywords:'',
		description:'',
	},
	globalSeo: {
		t: 'reg',
		k: 'reg',
		d: 'reg',
	},
})


export const mutations = {
	setUserInfo(state, userInfo) {
		state.userInfo = userInfo
		setCookie('USER_INFO', userInfo);
		setStore('USER_INFO', userInfo);

		state.isExhibitor = userInfo ? userInfo.roles.includes('ROLE_EXHIBITOR') : false;
		state.isReg = userInfo ? userInfo.roles.includes('ROLE_USER') : false;
		state.isGuest = userInfo ? false : true;
	},
	setSeo(state, seo) {
		state.seo = seo
	},
	logout(state) {
		removeCookie('USER_INFO');
		state.userInfo = null;
		removeAllStore();
	},
}

export const getters = {}

export const actions = {
	// nuxtServerInit方法会在服务端渲染被执行
	// cookie数据格式：key=value;key=value字符串
	nuxtServerInit({
		commit
	}, {
		req
	}) {
		if (process.server) {
			let userInfo = null
			// 如果请求头中有cookie数据
			if (req.headers.cookie) {
				// cookieparser.parse：就是把cookie格式字符串转化为一个对象
				// {key:value,key:value}
				const parsed = cookieparser.parse(req.headers.cookie)
				try {
					// 将Cookie中user的值转为JavaScript对象
					userInfo = JSON.parse(parsed.FRONT_USER_INFO)
				} catch (err) {
					// No valid cookie found
				}
			}
			commit('setUserInfo', userInfo)
		}
	},
}

export const modules = {
	app,
	data,
}
